// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

const path = require('path')
const exec = require('child_process').exec
let iconv = require('iconv-lite')

let $nginx = document.querySelector('#nginx')

let $bgi = document.querySelector('#bgi')

let $ini = document.querySelector('#ini')

let serverLog = document.querySelector('#serverLog')

let $start = document.querySelector('#start')

let $stop = document.querySelector('#stop')
let $cleanupLog = document.querySelector('#cleanupLog')

let encoding = 'cp936'
let binaryEncoding = 'binary'

let nginxIsStop

function serverLogAppend (text) {

  if (!text) {
    return
  }

  if (typeof text !== 'string') {
    return
  }

  text = text.trim()

  if (text === '') {
    return
  }

  let oldHtml = serverLog.innerHTML
  serverLog.innerHTML = oldHtml + text + '\n'
  // console.log(serverLog.scrollHeight)
  serverLog.scrollTop = serverLog.scrollHeight
}

function cleanupLog () {
  serverLog.innerHTML = ''
}

let phpFlag = false

function startNginx () {

  phpFlag = true
  serverLogAppend('Start')

  let nginxVal = $nginx.value
  let cgiVal = $bgi.value
  let iniVal = $ini.value

  var nginxPath = path.dirname(nginxVal)
  var nginxExe = path.basename(nginxVal)

  var cgiPath = path.dirname(cgiVal)
  var cgiExe = path.basename(cgiVal)
  serverLogAppend('正在启动NGINX')
  exec('start ' + nginxExe, {
    encoding: binaryEncoding,
    cwd: nginxPath
  }, function (error, stdout, stderr) {
    let stdoututf8 = iconv.decode(new Buffer(stdout, binaryEncoding), encoding)
    let stderrutf8 = iconv.decode(new Buffer(stderr, binaryEncoding), encoding)

    nginxIsStop = false

    serverLogAppend(stdoututf8)
    serverLogAppend(stderrutf8)

  })
  // phpStart(cgiExe, iniVal, cgiPath)
}

$start.addEventListener('click', function () {
  startNginx()

})

function stopNginx (cb) {
  phpFlag = false
  serverLogAppend('Stop')

  exec('taskkill /f /im nginx.exe', { encoding: binaryEncoding }, (error, stdout, stderr) => {

    let stdoututf8 = iconv.decode(new Buffer(stdout, binaryEncoding), encoding)
    let stderrutf8 = iconv.decode(new Buffer(stderr, binaryEncoding), encoding)

    serverLogAppend(stdoututf8)
    serverLogAppend(stderrutf8)
    nginxIsStop = true
    cb && cb()
  })
  // exec('taskkill /f /im php-cgi.exe', { encoding: binaryEncoding }, (error, stdout, stderr) => {
  //
  //   let stdoututf8 = iconv.decode(new Buffer(stdout, binaryEncoding), encoding)
  //   let stderrutf8 = iconv.decode(new Buffer(stderr, binaryEncoding), encoding)
  //
  //   serverLogAppend(stdoututf8)
  //   serverLogAppend(stderrutf8)
  //   phpIsStop = true
  //   cb && cb()
  // })
}

$stop.addEventListener('click', function () {
  stopNginx(function () {

  })
})

$cleanupLog.addEventListener('click', function () {
  cleanupLog()
})

stopNginx(function () {
  if (nginxIsStop) {
    startNginx()
  }
})
